<template>
  <page-header-wrapper>
    <a-card>
      <span style="font-size: 25px">{{ timeFix }}!</span>
    </a-card>
    <a-row :gutter="24" v-if="false">
      <!-- 总销售额 -->
      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card :loading="loading" title="总销售额" :total="'￥' + topData.sell.total_money">
          <a-tooltip title="指标说明" slot="action">
            <a-icon type="info-circle-o" />
          </a-tooltip>
          <div>
            <trend :flag="topData.sell.week_sell_percent.slice(0, 1) == '-' ? 'down' : 'up'" style="margin-right: 16px">
              <span slot="term">近七天</span>
              {{ topData.sell.week_sell_percent }}
            </trend>
            <trend :flag="topData.sell.day_sell_percent.slice(0, 1) == '-' ? 'down' : 'up'">
              <span slot="term">近24小时</span>
              {{ topData.sell.day_sell_percent }}
            </trend>
          </div>
          <template slot="footer"
            >日销售额<span>￥ {{ topData.sell.today_sell_money }}</span></template
          >
        </chart-card>
      </a-col>
      <!-- 商品总数 -->
      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card :loading="loading" title="商品总数" :total="topData.goods.total_goods">
          <a-tooltip title="指标说明" slot="action">
            <a-icon type="info-circle-o" />
          </a-tooltip>
          <div>
            <trend
              :flag="topData.goods.week_goods_percent.slice(0, 1) == '-' ? 'down' : 'up'"
              style="margin-right: 16px"
            >
              <span slot="term">近七天</span>
              {{ topData.goods.week_goods_percent }}
            </trend>
            <trend :flag="topData.goods.day_goods_percent.slice(0, 1) == '-' ? 'down' : 'up'">
              <span slot="term">近24小时</span>
              {{ topData.goods.day_goods_percent }}
            </trend>
          </div>
          <template slot="footer"
            >日新增 <span>{{ topData.goods.today_goods }}</span></template
          >
        </chart-card>
      </a-col>
      <!-- 用户总量 -->
      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card :loading="loading" :title="topData.mch_order_money?'商户订单金额':'用户总量'" :total="topData.mch_order_money?topData.mch_order_money.total_money:topData.user.total | NumberFormat">
          <a-tooltip title="指标说明" slot="action">
            <a-icon type="info-circle-o" />
          </a-tooltip>
          <div>
            <mini-area :asyncData="topData.mch_order_money?topData.mch_order_money.mch_order_money:topData.user.data" :scale="topData.mch_order_money?orderScale:searchUserScale" />
          </div>
          <template slot="footer"
            >{{topData.mch_order_money?'日销售额':'日新增'}}<span> {{ topData.mch_order_money?topData.mch_order_money.today_sell_money:topData.user.today_user | NumberFormat }}</span></template
          >
        </chart-card>
      </a-col>
      <!-- 订单总数 -->
      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card :loading="loading" title="订单总数" :total="topData.order.total | NumberFormat">
          <a-tooltip title="指标说明" slot="action">
            <a-icon type="info-circle-o" />
          </a-tooltip>
          <div>
            <mini-bar :asyncData="topData.order.data" :scale="searchUserScale" />
          </div>
          <template slot="footer"
            >日新增 <span>{{ topData.order.today_order }}</span></template
          >
        </chart-card>
      </a-col>
    </a-row>

    <a-card :loading="loading" :bordered="false" :body-style="{ padding: '0' }" v-if="false">
      <div class="salesCard">
        <a-tabs default-active-key="1" size="large" :tab-bar-style="{ marginBottom: '24px', paddingLeft: '16px' }">
          <div class="extra-wrapper" slot="tabBarExtraContent">
            <div class="extra-item">
              <a-radio-group v-model="timeRange">
                <a-radio-button value="a"> 近24小时 </a-radio-button>
                <a-radio-button value="b"> 近一周 </a-radio-button>
                <a-radio-button value="c"> 近30日 </a-radio-button>
              </a-radio-group>
            </div>
            <!-- <a-range-picker :style="{ width: '256px' }" /> -->
          </div>
          <a-tab-pane tab="订单走势" key="1">
            <a-row>
              <a-col :xl="centerRankData.length?16:24" :lg="12" :md="12" :sm="24" :xs="24">
                <bar :data="centerBarData" :scale="orderScale" title="销售趋势" />
              </a-col>
              <a-col :xl="centerRankData.length?8:0" :lg="12" :md="12" :sm="24" :xs="24">
                <rank-list title="门店最高排名" :list="centerRankData" />
              </a-col>
            </a-row>
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-card>

    <div class="antd-pro-pages-dashboard-analysis-twoColLayout" v-if="false">
      <a-row :gutter="24" type="flex" :style="{ marginTop: '24px' }">
        <a-col :xl="12" :lg="24" :md="24" :sm="24" :xs="24">
          <a-card :loading="loading" :bordered="false" title="商品销量" :style="{ height: '100%' }">
            <!-- <a-dropdown :trigger="['click']" placement="bottomLeft" slot="extra">
              <a class="ant-dropdown-link" href="#">
                <a-icon type="ellipsis" />
              </a>
              <a-menu slot="overlay">
                <a-menu-item>
                  <a href="javascript:;">操作一</a>
                </a-menu-item>
                <a-menu-item>
                  <a href="javascript:;">操作二</a>
                </a-menu-item>
              </a-menu>
            </a-dropdown> -->
            <a-row :gutter="68">
              <a-col :xs="24" :sm="12" :style="{ marginBottom: ' 24px' }">
                <number-info :total="currentLineData.paynum - 0">
                  <span slot="subtitle">
                    <span>商品销量趋势</span>
                    <a-tooltip title="指标说明" slot="action">
                      <a-icon type="info-circle-o" :style="{ marginLeft: '8px' }" />
                    </a-tooltip>
                  </span>
                </number-info>
                <!-- miniChart -->
                <div>
                  <mini-smooth-area
                    :style="{ height: '45px' }"
                    :dataSource="currentLineData.sell_data"
                    :scale="searchUserScale"
                  />
                </div>
              </a-col>
              <a-col :xs="24" :sm="12" :style="{ marginBottom: ' 24px' }">
                <number-info :total="currentLineData.cart - 0">
                  <span slot="subtitle">
                    <span>商品加购人数</span>
                    <a-tooltip title="指标说明" slot="action">
                      <a-icon type="info-circle-o" :style="{ marginLeft: '8px' }" />
                    </a-tooltip>
                  </span>
                </number-info>
                <!-- miniChart -->
                <div>
                  <mini-smooth-area
                    :style="{ height: '45px' }"
                    :dataSource="currentLineData.cart_data"
                    :scale="searchUserScale"
                  />
                </div>
              </a-col>
            </a-row>
            <div class="ant-table-wrapper">
              <s-table row-key="key" size="small" :columns="columns" :data="loadData" ref="table"> </s-table>
            </div>
          </a-card>
        </a-col>
        <a-col :xl="12" :lg="24" :md="24" :sm="24" :xs="24">
          <a-card
            class="antd-pro-pages-dashboard-analysis-salesCard"
            :loading="loading"
            :bordered="false"
            title="常用操作"
            :style="{ height: '100%' }"
          >
            <div class="item-group">
              <a href="javascript:;" @click="pushToRoute(item)" v-for="(item, index) in optionList" :key="index">{{
                item.title
              }}</a>
              <a-button size="small" type="primary" ghost icon="plus" @click="isShowOperationsModal = true"
                >添加</a-button
              >
            </div>
          </a-card>
        </a-col>
      </a-row>
    </div>
    <a-modal
      v-model="isShowOperationsModal"
      :width="720"
      :destroy-on-close="true"
      title="编辑快捷操作"
      @cancel="isShowOperationsModal = false"
      @ok="saveOperations"
    >
      <a-checkbox-group @change="onChange" :defaultValue="optionList.map((el) => el.name)">
        <a-row>
          <a-col :span="6" v-for="(item, index) in permissionTree" :key="index">
            <a-checkbox :value="item.key">
              {{ item.title }}
            </a-checkbox>
          </a-col>
        </a-row>
      </a-checkbox-group>
    </a-modal>
  </page-header-wrapper>
</template>

<script>
import moment from 'moment'
import {
  ChartCard,
  MiniArea,
  MiniBar,
  MiniProgress,
  RankList,
  Bar,
  Trend,
  NumberInfo,
  MiniSmoothArea,
} from '@/components'
import { dashboardData, dashboardOrderData, dashboardGoodsData, getOperations, saveOperations } from '@/api/dashboard'
import { STable } from '@/components'
import { getPermission } from '@/api/auth'
import { asyncRouterMap } from '@/config/router.config'
import { timeFix } from '@/utils/util'

const orderScale = [
  {
    dataKey: 'x',
    alias: '时间',
  },
  {
    dataKey: 'y',
    alias: '销售额',
    min: 0,
    max: 10,
  },
]
const searchUserScale = [
  {
    dataKey: 'x',
    alias: '时间',
  },
  {
    dataKey: 'y',
    alias: '数量',
    min: 0,
    max: 10,
  },
]
const columns = [
  {
    title: '排名',
    width: 20,
    customRender:(text,record,index) => index + 1
  },
  {
    title: '商品名称',
    dataIndex: 'name',
    width: 150,
    ellipsis: true,
  },
  {
    title: '商品销量',
    dataIndex: 'paynum',
    width: 100,
    align: 'center',
  },
  {
    title: '支付总金额',
    dataIndex: 'jine',
    width: 100,
    align: 'center',
  },
]
export default {
  name: 'Analysis',
  components: {
    STable,
    ChartCard,
    MiniArea,
    MiniBar,
    MiniProgress,
    RankList,
    Bar,
    Trend,
    NumberInfo,
    MiniSmoothArea,
  },
  data() {
    return {
      timeFix: timeFix(),
      asyncRouterMap,
      columns,
      orderScale,
      searchUserScale,
      permissionTree: [],
      dataOperations: [],
      isShowOperationsModal: false,
      currentLineData: {
        cart_data: [],
        sell_data: [],
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        let that = this
        return dashboardGoodsData({ ...parameter }).then((res) => {
          that.currentLineData = res.data.data[0]
          return res.data
        })
      },
      loading: false,
      topData: {
        goods: { total_goods: '2', today_goods: '0', week_goods_percent: '-', day_goods_percent: '-100.00%' },
        order: { total: '0', today_order: '7', data: [] },
        sell: { total_money: '2245.00', today_sell_money: '2245.00', week_sell_percent: '-', day_sell_percent: '-' },
        user: { total: '0', today_user: '2', data: [] },
      },
      centerBarData: [],
      centerRankData: [],
      checkedOperations: [],
      optionList: [],
      timeRange: 'a',
    }
  },
  computed: {
    timePickerOption() {
      switch (this.timeRange) {
        case 'a':
          return {}
        case 'b':
          return {
            start_time: moment().subtract(1, 'weeks').format('YYYY-MM-DD HH:mm:ss'),
            end_time: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
          }
        case 'c':
          return {
            start_time: moment().subtract(1, 'months').format('YYYY-MM-DD  HH:mm:ss'),
            end_time: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
          }
        default:
          return {}
      }
    },
  },
  created() {
    // this.loading = true
    // this.getTopData()
    // this.getCenterData()
    // this.getOperationsData()
    // getPermission({}).then((res) => {
    //   this.permissionTree = res.data
    // })
    // setTimeout(() => {
    //   this.loading = false
    // }, 1000)
  },
  watch: {
    // timeRange(val) {
    //   this.getCenterData()
    // },
  },
  methods: {
    moment,
    pushToRoute(item) {
      this.$router.push({ name: item.route })
    },
    async saveOperations() {
      try {
        const res = await saveOperations({ text: this.dataOperations })
        this.$message.success('保存成功')
        this.isShowOperationsModal = false
        this.getOperationsData()
      } catch (error) {}
    },
    filterData() {
      let resArr = []
      this.checkedOperations.forEach((item) => {
        this.asyncRouterMap[0].children.forEach((el) => {
          if (el.meta && el.meta.permission) {
            if (item == el.meta.permission[0]) {
              resArr.push({
                name: item,
                route: el.name,
                title: el.meta.title,
              })
            }
          }
        })
      })
      this.dataOperations = resArr
    },
    onChange(checkedValues) {
      console.log('checked = ', checkedValues)
      this.checkedOperations = checkedValues
      this.filterData()
    },
    async getOperationsData() {
      try {
        const res = await getOperations({})
        this.optionList = res.data
      } catch (error) {}
    },
    async getTopData() {
      try {
        const res = await dashboardData({})
        this.topData = res.data
      } catch (error) {
        console.log('🚀 ~ file: Analysis.vue ~ line 386 ~ getTopData ~ error', error)
      }
    },
    async getCenterData() {
      console.log({ ...this.timePickerOption })
      try {
        const res = await dashboardOrderData({ ...this.timePickerOption })
        if (res.data.length == 24) {
          res.data.forEach((item) => {
            item.x = item.x.slice(11, 16)
            item.y = item.y - 0
          })
        } else {
          res.data.forEach((item) => {
            item.x = item.x.slice(6, 10)
            item.y = item.y - 0
          })
        }
        res.data.reverse()
        this.centerBarData = res.data
        this.centerRankData = res.shop_list
        console.log('🚀 ~ file: Analysis.vue ~ line 392 ~ getCenterData ~ res', res)
      } catch (error) {}
    },
  },
}
</script>

<style lang="less" scoped>
.item-group {
  padding: 0 0 8px 24px;
  font-size: 0;

  a {
    color: rgba(0, 0, 0, 0.65);
    display: inline-block;
    font-size: 14px;
    margin-bottom: 13px;
    width: 25%;
    &:hover{
      color:rgb(24, 144, 255)
    }
  }
}
.extra-wrapper {
  line-height: 55px;
  padding-right: 24px;

  .extra-item {
    display: inline-block;
    margin-right: 24px;

    a {
      margin-left: 24px;
    }
  }
}

.antd-pro-pages-dashboard-analysis-twoColLayout {
  position: relative;
  display: flex;
  display: block;
  flex-flow: row wrap;
}

.antd-pro-pages-dashboard-analysis-salesCard {
  height: calc(100% - 24px);
  /deep/ .ant-card-head {
    position: relative;
  }
}

.dashboard-analysis-iconGroup {
  i {
    margin-left: 16px;
    color: rgba(0, 0, 0, 0.45);
    cursor: pointer;
    transition: color 0.32s;
    color: black;
  }
}
.analysis-salesTypeRadio {
  position: absolute;
  right: 54px;
  bottom: 12px;
}
</style>
